package com.netkit.message;

import java.nio.ByteBuffer;

import org.jboss.netty.buffer.ChannelBuffer;

import com.netkit.exception.MessageConvertException;

public class MessageDecoder {
	
	public static Message decode(byte[] bytes)throws MessageConvertException{
		return decode(ByteBuffer.wrap(bytes));
	}
	
	public static Message decode(ByteBuffer buffer)throws MessageConvertException{
		int sourceLen =buffer.arrayOffset() + buffer.limit();
		if(sourceLen < Message.HEADER_SIZE){
			throw new MessageConvertException("Message header length error.");
		}
		
		int messageId = buffer.getInt();
		int dataLen = buffer.getInt();
		if(sourceLen < dataLen + Message.HEADER_SIZE){
			throw new MessageConvertException("Message data length error.");
		}
		
		byte[] bytes = null;
		if(dataLen > 0){
			bytes = new byte[dataLen];
			buffer.get(bytes);
		}
		return new Message(messageId,bytes);
	}
	
	public static Message decode(ChannelBuffer buffer)throws MessageConvertException{
		if(buffer.readableBytes() <  Message.HEADER_SIZE){
			throw new MessageConvertException("Message header length error.");
		}
		int messageId = buffer.readInt();
		int contentLen = buffer.readInt();
		if(buffer.readableBytes() < contentLen){
			throw new MessageConvertException("Message data length error.");
		}
		
		byte[] bytes = null;
		if(contentLen > 0){
			bytes = new byte[contentLen];
			buffer.readBytes(bytes);
		}
		
		return new Message(messageId,bytes);
	}
}
